class StoresController < ApplicationController
  before_filter :login_required, :except => [:index, :show]
  
  def index
    @stores = Store.find :all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @stores }
    end
  end

  def show
    @store = Store.find(params[:id])
    @google_map_key = google_map_key
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @store }
    end
  end

  def new
    @store = Store.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @store }
    end
  end

  def edit
    @store = Store.find(params[:id])
  end

  def create
    @store = Store.new(params[:store])
    @product_shot = ProductShot.new(params[:product_shot])
    
    respond_to do |format|
      if @store.save && @product_shot.save
        current_user.stores << @store
        @store.update_attributes(:image => @product_shot.public_filename)
        flash[:notice] = 'Store was successfully created.'
        format.html { redirect_to(:controller => :stores, :action => :products, :id => @store.id) }
        format.xml  { render :xml => @store, :status => :created, :location => @store }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @store.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @store = Store.find(params[:id])

    respond_to do |format|
      if @store.update_attributes(params[:store])
        flash[:notice] = 'Store was successfully updated.'
        format.html { redirect_to(@store) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @store.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @store = Store.find(params[:id])
    @store.destroy

    respond_to do |format|
      format.html { redirect_to(admin_stores_url) }
      format.xml  { head :ok }
    end
  end
  
  def products
    @store = Store.find(params[:id])
    @products = Product.find :all
  end
  
  def add_product
    store = Store.find(params[:store_id])
    product = Product.find(params[:product_id])
    store.products << product
    render :inline => "Done."
  end
  
  def remove_product
    store = Store.find(params[:store_id])
    product = Product.find(params[:product_id])
    store.products.delete(product)
    render :inline => "Done."
  end
end
